package net.dgi.common.match.impl;

import net.dgi.common.ioc.Inject;
import net.dgi.common.ioc.InjectSource;
import net.dgi.common.ioc.Injector;

import java.util.List;

/**
 * Viva IntelliJ IDEA.
 * User: Deian Date: Sep 30, 2010 Time: 8:59:19 PM
 */
public class Matcher implements Runnable {
    @Inject(InjectSource.SHARE)
    protected MatchContext context;

    @Inject(InjectSource.SHARE)
    protected FunctionRegistry functionRegistry;

    public Matcher() {
        Injector.inject(this);
    }

    public void run() {
        for (; ;) {
            if (context.hasShutdownSignal) {
                return;
            }
            MatchRequest matchRequest = context.incomingQueue.poll();
            try {
                if (matchRequest == null) {
                    wait();
                }
                Class ticketClass = matchRequest.getData().getClass();
                List<Function> functions = functionRegistry.get(ticketClass);
                if (functions == null) {
                    context.outgoingQueue.add(new MatchResult(matchRequest, new Exception("No matching function")));
                    return;
                }

                for (Function function : functions) {
                    MatchAssignment task = new MatchAssignment(function, matchRequest);
                    context.executionQueue.add(task);
                }
            } catch (InterruptedException e) {
                continue;
            } catch (Exception e) {
                context.incomingQueue.add(matchRequest);
            }
        }
    }
}
